/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package be.fedict.barth.signer;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;

/**
 *
 * @author hanssens_bart
 */
public class Util {
    public static final ASN1ObjectIdentifier SHA256 = NISTObjectIdentifiers.id_sha256;

    
    public static String getSignerName(X509Certificate cert) throws InvalidNameException {
        String name = "";
        String dn = cert.getSubjectX500Principal().getName();
        
        LdapName ldap = new LdapName(dn);
        for (Rdn rdn : ldap.getRdns()) {
            if (rdn.getType().equals("CN")) {
                name = rdn.getValue().toString();
            }
        }
        return name;
    }
    
    public static HttpURLConnection Get(URL url) throws IOException {
        InetSocketAddress server = new InetSocketAddress("proxy2.yourict.net", 8080);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, server);     
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
        
        conn.setRequestMethod("GET");
        
        return conn;
    }
    
    public static HttpURLConnection Post(URL url, String request, String response, byte[] b) throws ProtocolException, IOException {
        //HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InetSocketAddress server = new InetSocketAddress("proxy2.yourict.net", 8080);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, server);     
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
        
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", request);
        conn.setRequestProperty("Content-Length", String.valueOf(b.length));
        conn.setRequestProperty("Accept", response);

        conn.setDoOutput(true);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(b);
        dos.flush();
        dos.close();
        
        return conn;
    }
}
